package com.ruoyi.system.service.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.modbus.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.vo.IotGatewayVo;
import com.ruoyi.system.mapper.IotDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.IotGatewayMapper;
import com.ruoyi.system.domain.IotGateway;
import com.ruoyi.system.service.IIotGatewayService;

/**
 * 网关Service业务层处理
 * 公司名称：未可自动化 <br/>
 * 作者：weikeauto <br/>
 */
@Service
public class IotGatewayServiceImpl implements IIotGatewayService 
{
    @Autowired
    private IotGatewayMapper iotGatewayMapper;


    @Autowired
    private IotDeviceMapper iotDeviceMapper;

    /**
     * 查询网关
     * 
     * @param id 网关主键
     * @return 网关
     */
    @Override
    public IotGateway selectIotGatewayById(Long id)
    {
        return iotGatewayMapper.selectIotGatewayById(id);
    }

    /**
     * 查询网关列表
     * 
     * @param iotGateway 网关
     * @return 网关
     */
    @Override
    @DataScope(deptAlias = "sd")
    public List<IotGatewayVo> selectIotGatewayList(IotGateway iotGateway) {
        List<IotGatewayVo> iotGatewayVoList = iotGatewayMapper.selectNewIotGatewayList(iotGateway);
        for (IotGatewayVo iotGatewayVo : iotGatewayVoList) {
            if (CacheUtils.get(iotGatewayVo.getSn()) != null) {
                iotGatewayVo.setGatewayStatus(0L);
            }else{
                iotGatewayVo.setGatewayStatus(1L);
            }
        }
        return iotGatewayVoList;
    }

    /**
     * 新增网关
     * 
     * @param iotGateway 网关
     * @return 结果
     */
    @Override
    public int insertIotGateway(IotGateway iotGateway) {
        // 校验数据重复性
        int gatewayNameCount = iotGatewayMapper.selectIotGatewayByName(iotGateway.getGatewayName());
        if (gatewayNameCount > 0) {
            throw new ServiceException("网关名称重复");
        }
        int gatewaySnCount = iotGatewayMapper.selectIotGatewayBySn(iotGateway.getSn());
        if (gatewaySnCount > 0) {
            throw new ServiceException("网关SN重复");
        }
        iotGateway.setCreateTime(DateUtils.getNowDate());
        iotGateway.setHeartBeatStr("aa" + convertToHex(iotGateway.getSn().trim()) + "aa");
        return iotGatewayMapper.insertIotGateway(iotGateway);
    }

    public static String convertToHex(String str) {
        StringBuilder hex = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            String hexString = Integer.toHexString(c);
            hex.append(hexString);
        }
        return hex.toString();
    }

    public static String convertFromHex(String hexString) {
        StringBuilder result = new StringBuilder();

        // 每2个字符一组进行处理（因为一个字节用2个16进制字符表示）
        for (int i = 0; i < hexString.length(); i += 2) {
            // 提取两个16进制字符
            String hexPair = hexString.substring(i, Math.min(i + 2, hexString.length()));

            // 将16进制转换为十进制，然后转换为字符
            int charCode = Integer.parseInt(hexPair, 16);
            result.append((char) charCode);
        }

        return result.toString();
    }

    /**
     * 修改网关
     * 
     * @param iotGateway 网关
     * @return 结果
     */
    @Override
    public int updateIotGateway(IotGateway iotGateway)
    {
        iotGateway.setUpdateTime(DateUtils.getNowDate());
        iotGateway.setHeartBeatStr("aa" + convertToHex(iotGateway.getSn().trim()) + "aa");
        return iotGatewayMapper.updateIotGateway(iotGateway);
    }

    /**
     * 批量删除网关
     * 
     * @param ids 需要删除的网关主键
     * @return 结果
     */
    @Override
    public int deleteIotGatewayByIds(Long[] ids)
    {
        // 校验 如果网关被设备应用就不能删除
        int deviceCount = iotDeviceMapper.selectDeviceByGatawayIds(ids);
        if(deviceCount > 0){
            throw  new ServiceException("此网关已被设备引用，请先删除引用网关的设备");
        }
        return iotGatewayMapper.deleteIotGatewayByIds(ids);
    }

    /**
     * 删除网关信息
     * 
     * @param id 网关主键
     * @return 结果
     */
    @Override
    public int deleteIotGatewayById(Long id)
    {
        return iotGatewayMapper.deleteIotGatewayById(id);
    }

    @Override
    public Map<String, Integer> statistics() {
        IotGateway iotGateway = new IotGateway();
        List<IotGatewayVo> iotGatewayVoList = iotGatewayMapper.selectNewIotGatewayList(iotGateway);
        for (IotGatewayVo iotGatewayVo : iotGatewayVoList) {
            if (CacheUtils.get(iotGatewayVo.getSn()) != null) {
                iotGatewayVo.setGatewayStatus(0L);
            } else {
                iotGatewayVo.setGatewayStatus(1L);
            }
        }
        Map<Long, Long> iotGatewayCount = iotGatewayVoList.stream()
                .collect(Collectors.groupingBy(IotGatewayVo::getGatewayStatus, Collectors.counting()));

        Map<String, Integer> countMap = new HashMap<>(4);
        countMap.put("total", iotGatewayVoList.size());
        countMap.put("online", iotGatewayCount.get(0L) == null ? 0 : iotGatewayCount.get(0L).intValue());
        countMap.put("offline", iotGatewayCount.get(1L) == null ? 0 : iotGatewayCount.get(1L).intValue());
        return countMap;
    }

    @Override
    public List<IotGateway> selectAllIotGatewayList() {
        return iotGatewayMapper.selectAllIotGatewayList();
    }

    public static void main(String[] args) {
        String hex= "3030313030353235303730333030303635343735";
        System.out.println(convertFromHex(hex));
    }


}
